#include "tablecurdtemplate.h"
//#include <QHeaderView>
//#include <QMessageBox>
#include "recorddetailtemplate.h"
#include "dnsuffixwhoismappingdlg.h"



TableCURDTemplate::TableCURDTemplate(QWidget *parent)
    : QWidget{parent}
{
    m_dlg = static_cast<DNSuffixWhoisMappingDlg *>(QWidget::parentWidget());

    //initModel();


}

TableCURDTemplate::~TableCURDTemplate()
{

}

void TableCURDTemplate::initUi()
{

    /*-----------------设置查询区--------------------*/
    m_filterWidget = new QWidget(this);
    m_hFilterLayout = new QHBoxLayout();

    if(m_editEnable)
    {
        m_lableEdit = new QLabel(this);
        m_lableEdit->setText("请输入");
        m_lableEdit->setMaximumHeight(40);
        m_lableEdit->setAlignment(Qt::AlignCenter);
        m_hFilterLayout->addWidget(m_lableEdit,1);

        m_editText = new QLineEdit(this);
        m_hFilterLayout->addWidget(m_editText,2);
    }

    if(m_combEnable)
    {
        m_labelComb = new QLabel(this);
        m_labelComb->setText("请选择");
        m_labelComb->setMaximumHeight(40);
        m_labelComb->setAlignment(Qt::AlignCenter);
        m_hFilterLayout->addWidget(m_labelComb,1);

        m_combSelect = new QComboBox(this);
        m_hFilterLayout->addWidget(m_combSelect,2);
    }

    if(m_sdateEnable)
    {
        m_labelStart = new QLabel(this);
        m_labelStart->setText("开始日期");
        m_labelStart->setMaximumHeight(40);
        m_labelStart->setAlignment(Qt::AlignCenter);
        m_hFilterLayout->addWidget(m_labelStart,1);

        m_dateStart = new QDateEdit(this);
        m_dateStart->setCalendarPopup(true);
        m_hFilterLayout->addWidget(m_dateStart,2);
    }

    if(m_edateEnable)
    {
        m_labelEnd = new QLabel(this);
        m_labelEnd->setText("结束日期");
        m_labelEnd->setMaximumHeight(40);
        m_labelEnd->setAlignment(Qt::AlignCenter);
        m_hFilterLayout->addWidget(m_labelEnd,1);

        m_dateEnd = new QDateEdit(this);
        m_dateEnd->setCalendarPopup(true);
        m_hFilterLayout->addWidget(m_dateEnd,2);
    }
    if(m_edateEnable||m_editEnable||m_sdateEnable||m_combEnable)
    {
        m_btnQry = new QPushButton(this);
        m_btnQry->setText("查询");
        m_hFilterLayout->addWidget(m_btnQry,1);

        m_btnReset = new QPushButton(this);
        m_btnReset->setText("重置");
        m_hFilterLayout->addWidget(m_btnReset,1);

        connect(m_btnQry, &QPushButton::clicked, this, &TableCURDTemplate::slotQryRecords);
        connect(m_btnReset, &QPushButton::clicked, this, &TableCURDTemplate::slotResetFilter);
    }

    m_filterSpacer = new QSpacerItem(200, 20, QSizePolicy::Minimum, QSizePolicy::Expanding);
    m_hFilterLayout->addSpacerItem(m_filterSpacer);

    m_hFilterLayout->setContentsMargins(0,0,0,0);
    m_hFilterLayout->setStretch(10,4);


    m_filterWidget->setMaximumHeight(40);
    m_filterWidget->setLayout(m_hFilterLayout);
    //m_filterWidget->setStyleSheet("background-color: blue");
    //m_filterWidget->setStyleSheet("border: 1px solid grey");
    /*----------------设置操作区域----------------------------------*/
    m_actWidget = new QWidget(this);
    m_hActLayout = new QHBoxLayout();

    m_btnAdd = new QPushButton(this);
    m_btnAdd->setText("增加");
    m_hActLayout->addWidget(m_btnAdd,1);

    m_btnDel = new QPushButton(this);
    m_btnDel->setText("删除");
    m_hActLayout->addWidget(m_btnDel,1);

    m_btnMod = new QPushButton(this);
    m_btnMod->setText("修改");
    m_hActLayout->addWidget(m_btnMod,1);

    m_btnExp = new QPushButton(this);
    m_btnExp->setText("导出");
    m_hActLayout->addWidget(m_btnExp,1);

    m_actSpacer = new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding);
    m_hActLayout->addSpacerItem(m_actSpacer);

    m_hActLayout->setContentsMargins(0,0,0,0);
    m_hActLayout->setStretch(4,10);
    m_hActLayout->setSpacing(10);

    m_actWidget->setLayout(m_hActLayout);

    //m_actWidget->setStyleSheet("background-color: red");
    //m_actWidget->setStyleSheet("border: 1px solid grey");
    m_actWidget->setMaximumHeight(40);
    /*------------------设置显示区域--------------------------------------------*/
    m_showWidget = new QWidget(this);
    m_vShowLayout = new QVBoxLayout;

    m_tableView = new QTableView(this);
    m_vShowLayout->addWidget(m_tableView,10);

    m_pageBar = new QPageBar(this);

    m_vShowLayout->addWidget(m_pageBar,1);
    m_vShowLayout->setContentsMargins(0,0,0,0);

    m_showWidget->setLayout(m_vShowLayout);
    //m_showWidget->setStyleSheet("background-color: yellow");
    //m_showWidget->setStyleSheet("border: 1px solid grey");
    /*----------------设置整体布局----------------------------------*/
    m_vLayout  = new QVBoxLayout;

    m_vLayout->addWidget(m_filterWidget,1);
    m_vLayout->addWidget(m_actWidget,1);
    m_vLayout->addWidget(m_showWidget,8);
    m_vLayout->setContentsMargins(0,0,0,0);
    this->setLayout(m_vLayout);
    setStyleSheet("background-color: #F5F5F5");

    connect(m_btnAdd, &QPushButton::clicked, this, &TableCURDTemplate::slotAddRecord);
    connect(m_btnDel, &QPushButton::clicked, this, &TableCURDTemplate::slotDelRecord);
    connect(m_btnMod, &QPushButton::clicked, this, &TableCURDTemplate::slotModRecord);
    connect(m_btnExp, &QPushButton::clicked, this, &TableCURDTemplate::slotExpRecord);

}

void TableCURDTemplate::initModel()
{

    if(!m_db.isOpen())
    {
        qDebug()<<"数据库实例初始化失败!"<<m_db.isOpen();
        return;
    }
    if(m_pageSize==0)
    {
        qDebug()<<"表单分页数据未初始化!"<<m_pageSize;
        return;
    }
//    if(m_tableSql.isEmpty())
//    {
//        qDebug()<<"数据查询sql未设置!"<<m_tableSql;
//        return;
//    }
    if(m_strColsName.isEmpty())
    {
        qDebug()<<"列名未设置!";
        return;
    }
    if(!getTabTotalRecs(m_totalRecs))
        return;


    // 初始化域名详情模型
    m_tableModel = new QStandardItemModel;

    m_tableView->setSelectionBehavior(QAbstractItemView::SelectRows);//行选中
    m_tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);//不可编辑
    // m_tableView->horizontalHeader()->setStyleSheet("QHeaderView::section {/*background-color:#1E90FF;*/font:10pt '微软雅黑';}");//标题栏样式
    m_tableView->horizontalHeader()->setFixedHeight(35);//标题栏行高
    m_tableView->verticalHeader()->setDefaultSectionSize(25);//设置列的行高
    m_tableModel->setHorizontalHeaderLabels(m_strColsName);

    m_tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    m_tableView->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents);

    m_tableView->setModel(m_tableModel);

    m_pageBar->m_pageRecCount = m_pageSize;
    m_pageBar->m_recTotalCount =m_totalRecs;
    m_pageBar->m_pageTotalCount = (m_pageBar->m_recTotalCount - 1) / m_pageBar->m_pageRecCount + 1;
    if (m_pageBar->m_pageTotalCount >= 3)
        m_pageBar->setCount(m_pageBar->m_pageTotalCount, 3);
    else
        m_pageBar->setCount(m_pageBar->m_pageTotalCount, m_pageBar->m_pageTotalCount);

    connect(m_pageBar, &QPageBar::pageChanged, this, [&](int idx) {slotShowTabInfoByPage(-1,idx);});
    slotShowTabInfoByPage(0,1);
}

void TableCURDTemplate::setFilterControl(bool edit, bool comb, bool sdate, bool edate)
{
    m_editEnable=edit;
    m_combEnable=comb;
    m_sdateEnable= sdate;
    m_edateEnable = edate;
}

bool TableCURDTemplate::getTabTotalRecs(int &totalnum)
{
//    int index=m_tableSql.indexOf("from");
//    QString str = m_tableSql.mid(index);
    QString strSql = "select count(*) from "+ m_sqlTable+" "+m_sqlWhere;
    //qDebug()<<strSql;
    QSqlQuery query(m_db);
    query.prepare(strSql);
    if (query.exec() && query.next())
    {
        totalnum =query.value(0).toInt();
        //qDebug()<<"记录总数"<<m_totalRecs;
        return true;
    }
    else
    {
        qDebug() << "Failed to getTabTotalRecs: " << query.lastError().text();
        return false;
    }
}
void TableCURDTemplate::slotShowTabInfoByPage(int indexId,int curPage)
{
    //qDebug()<<indexId<<curPage;

    QSqlQuery query(m_db);

    QString strSql = "select "+ m_sqlCols + " from " + m_sqlTable+" "+m_sqlWhere +m_sqlOrder+ " limit ?,? ";
    query.prepare(strSql);
//   query.addBindValue(categoryId);
//    int a =m_pageSize*(curPage-1);
//    int b = m_pageSize;
    //qDebug()<<a<<b<<curPage<<pageSize;
    query.addBindValue(m_pageSize*(curPage-1));
    query.addBindValue(m_pageSize);
    //qDebug()<<strSql;
    if (!query.exec())
    {
        qDebug() << "Failed to execute query: " << query.lastError().text();
        return ;
    }
    m_tableModel->removeRows(0, m_tableModel->rowCount());
    QStringList colsName = m_sqlCols.split(",");
    int colsNum = colsName.size();
    while (query.next())
    {
        QList<QStandardItem *> rowItems;
        for(int i=0;i<colsNum;i++)
        {
            if(i==0)
                rowItems.append(new QStandardItem(QString::number(query.value(0).toInt())));
            else
                rowItems.append(new QStandardItem(query.value(i).toString()));
//            rowItems.append(new QStandardItem(query.value(2).toString()));
//            rowItems.append(new QStandardItem(query.value(3).toString()));
        }
        m_tableModel->appendRow(rowItems);
    }
}

void TableCURDTemplate::slotAddRecord()
{
    qDebug() <<"slotAddRecord";

    QSize mainWindowSize = m_dlg->size();

    QSize dialogSize = QSize(mainWindowSize.width()*0.5, mainWindowSize.height());
    RecordDetailTemplate dlg;
    // 设置对话框的大小
    dlg.setFixedSize(dialogSize);

    // 居中显示对话框
    QRect screenGeometry = m_dlg->geometry();
    QPoint centerPos = screenGeometry.center() - QPoint(mainWindowSize.width() / 2, mainWindowSize.height() / 2+30);
    dlg.move(centerPos);
    QList<QString> sval;
    dlg.initUi(m_strColsName,sval);
    dlg.exec();

    QList<QString> upValue =dlg.m_valueList;
    //qDebug()<<upValue;
    if(upValue.size()==0)
        return;
    QStringList colsName = m_sqlCols.split(",");
    int colsNum = colsName.size();
    QString strvalue="";
    for(int i=0;i<colsNum;i++)
    {
        if(i==colsNum-1)//ID自增字段
            strvalue+="?";
        else
            strvalue+="?,";
    }

    QString strSql = "insert into  "+ m_sqlTable + " ( "+m_sqlCols + " ) values(" +strvalue +" )";
    //qDebug()<<strSql;
    QSqlQuery query(m_db);
    query.prepare(strSql);
    for(int j=0;j<colsNum;j++)
    {
        //qDebug()<<upValue.at(j);
        if(j==0)
            query.addBindValue(0);
        else
            query.addBindValue(upValue.at(j));
    }
    if (!query.exec())
    {
        qDebug() << "Failed to slotAddRecord: " << query.lastError().text();
        return ;
    }
    slotShowTabInfoByPage(0,1);
    return ;

}

void TableCURDTemplate::slotDelRecord()
{
    qDebug() <<"slotDelRecord";
    QModelIndex selectedIndex = m_tableView->selectionModel()->currentIndex();
    if (!selectedIndex.isValid()) {
        QMessageBox::warning(this, "警告", "请选择一条记录删除！");
        return;
    }

    QStandardItem *itemId = m_tableModel->item(selectedIndex.row(),0);
    int recId = itemId->text().toInt();

    QStandardItem *itemName = m_tableModel->item(selectedIndex.row(),1);

    QString infostr ="是否要删除该记录:"+itemName->text();
    QMessageBox::StandardButton result= QMessageBox::question(this,"提示",infostr);
    if(result==QMessageBox::Yes)
    {
        QString strSql = "delete from  "+ m_sqlTable + " where id ="+QString::number(recId);
        qDebug()<<strSql;
        QSqlQuery query(m_db);
        query.prepare(strSql);
        if (!query.exec())
        {
            qDebug() << "Failed to slotDelRecord: " << query.lastError().text();
            return ;
        }
        m_tableModel->removeRow(selectedIndex.row(), selectedIndex.parent());
    }
}

void TableCURDTemplate::slotModRecord()
{
    qDebug() <<"slotModRecord";
    QModelIndex selectedIndex = m_tableView->selectionModel()->currentIndex();
    if (!selectedIndex.isValid()) {
        QMessageBox::warning(this, "警告", "请选择一条记录删除！");
        return;
    }
    int num = m_tableModel->columnCount();
    QList<QString> sval;
    QStandardItem *itemName;
    for(int i=0;i<num;i++)
    {
        itemName = m_tableModel->item(selectedIndex.row(),i);
        qDebug()<<itemName->text();
        sval.append(itemName->text());
    }

    QSize mainWindowSize = m_dlg->size();

    QSize dialogSize = QSize(mainWindowSize.width()*0.5, mainWindowSize.height());
    RecordDetailTemplate dlg;
    // 设置对话框的大小
    dlg.setFixedSize(dialogSize);

    // 居中显示对话框
    QRect screenGeometry = m_dlg->geometry();
    QPoint centerPos = screenGeometry.center() - QPoint(mainWindowSize.width() / 2, mainWindowSize.height() / 2+30);
    dlg.move(centerPos);
    dlg.initUi(m_strColsName,sval);
    dlg.exec();
    QList<QString> upValue =dlg.m_valueList;
    //qDebug()<<upValue;
    if(upValue.size()==0)
        return;

    QStringList colsName = m_sqlCols.split(",");
    int colsNum = colsName.size();
    QString strvalue="";
    for(int i=1;i<colsNum;i++)
    {
        if(i==colsNum-1)//ID自增字段
            strvalue+=colsName.at(i)+"='"+upValue.at(i)+"'";
        else
            strvalue+=colsName.at(i)+"='"+upValue.at(i)+"',";
    }

    QString strSql = "update "+ m_sqlTable + " set " + strvalue + " where id ="+upValue.at(0);
    qDebug()<<strSql;
    QSqlQuery query(m_db);
    query.prepare(strSql);
    if (!query.exec())
    {
        qDebug() << "Failed to slotModRecord: " << query.lastError().text();
        return ;
    }
    slotShowTabInfoByPage(0,1);
    return ;
}

void TableCURDTemplate::slotExpRecord()
{
    qDebug() <<"slotExpRecord";
    QMessageBox::StandardButton result= QMessageBox::question(this,"提示","还没做！");
}

void TableCURDTemplate::slotQryRecords()
{
    qDebug() <<"slotQryRecords";
    QMessageBox::StandardButton result= QMessageBox::question(this,"提示","还没做！");
}

void TableCURDTemplate::slotResetFilter()
{
    qDebug() <<"slotResetFilter";
    QMessageBox::StandardButton result= QMessageBox::question(this,"提示","还没做！");
}

